package com.jiangtai.training.ui.setting

import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.jiangtai.training.R
import com.jiangtai.training.base.BaseFragment
import com.jiangtai.training.constant.Constant
import com.jiangtai.training.dialog.ConfirmDialog
import com.jiangtai.training.dialog.SaveDialog
import com.jiangtai.training.event.ClearEvent
import com.jiangtai.training.net.MyRetrofit
import com.jiangtai.training.util.Preference
import kotlinx.android.synthetic.main.fragment_setting.*
import org.greenrobot.eventbus.EventBus
import org.litepal.LitePal

/**
 * Created by heCunCun on 2021/3/10
 */
class SettingFragment : BaseFragment() {

    private var phoneId: String by Preference(Constant.PHONE_ID, "")
    private var serverIp: String by Preference(Constant.SERVER_IP, "")
    private var phoneIp: String by Preference(Constant.PHONE_IP, "")
    private var currentTaskId: String by Preference(Constant.CURRENT_TASK_ID, "")
    override fun attachLayoutRes(): Int = R.layout.fragment_setting

    override fun initView(view: View) {

        iv_save.setOnClickListener {
          val pid = et_phone_id.text.toString().trim()
            if (pid.isNotEmpty() && pid.toInt()>=0 && pid.toInt()<=99) {
                phoneId = et_phone_id.text.toString().trim()
            }else{
                ToastUtils.showShort("ID 范围0-99,请重新设置")
                et_phone_id.setText(phoneId)
                return@setOnClickListener
            }
            val currentIP = et_serve_ip.text.toString().trim()
            if (currentIP != serverIp){
                serverIp = currentIP
                MyRetrofit.resetInstance()
            }

            phoneIp =(et_phone_ip.text.toString().trim())
            SaveDialog(requireContext()).show()
        }
        tv_del_task.setOnClickListener {
            //结束考核
            val finishDialog = ConfirmDialog(
                requireContext(), "清空所有任务",
                "即将清空所有任务列表及数据，如您已经不需要任何任务数据,请点击完成。", "完成"
            )
            finishDialog.show()
            finishDialog.setonConfirmListen(object : ConfirmDialog.OnConfirmListener {
                override fun onConfirm() {
                    LitePal.deleteDatabase("training")
                    currentTaskId=""
                    ToastUtils.showShort("清空成功")
                    EventBus.getDefault().post(ClearEvent())
                    LitePal.getDatabase()
                    finishDialog.dismiss()
                }

            })

        }
    }

    override fun lazyLoad() {
        et_phone_id.setText(phoneId)
        et_serve_ip.setText(serverIp)
        et_phone_ip.setText(phoneIp)
    }

    companion object {
        fun getInstance(): SettingFragment = SettingFragment()
    }
}